define([
    'underscore',
    'backbone',
    '../model/goods',
    'template',
    'text!../tmpl/goods.html'
],function(_,Backbone,GoodsModel,Template,GoodsTmpl){
    var GoodsView = Backbone.View.extend({
        tagName:'div',
        className:'goods-item',
        template:Template.compile(GoodsTmpl),
        initialize:function(model,option){

            //重要，绑定当前对象的render,unrender,不然model.bind时，无法调用当前对象的的方法中的this
            _.bindAll(this, 'render', 'unrender');

            //model内容改变时，重新渲染视图
            this.model.bind('change', this.render);
            this.model.bind('destroy', this.unrender);
            //this.render();
        },
        //事件绑定
        events:{
            //减少数量
            'click .sub':'operation_sub',
            //增加数量
            'click .add':'operation_add',
            //选择
            'click .toggle'   : 'toggleDone',
            //删除
            'click .remove'   : 'clear'

        },
        operation_sub:function () {
            //alert('operation_sub' + this.model.get('quantity'));
            this.model.set('quantity',this.model.get('quantity')-1);
        },
        operation_add:function () {
            //alert('add');
            this.model.set('quantity',this.model.get('quantity')+1);

        },
        update_quantity:function (item) {
            this.$('.quantity').html(item.changed.quantity);
        },
        clear:function () {
            this.model.destroy();
        },
        toggleDone: function() {
            this.model.toggle();
        },
        //输出渲染
        render: function () {
            var html = this.template(this.model.toJSON());
            this.$el.html(html);
            return this;
        },
        unrender:function () {
            this.$el.remove();
        }
    });
    return GoodsView;
});